<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>props</title>

</head>

<body>
    <div id="app">
        <div @click="num++">来自子组件的数据：{{message}}</div>
        <button @click="changeMessage">修改子组件的数据</button>

        <button @click="changeNumInParent">修改子组件的count数据</button>

        <!-- 自定义事件名称不要和系统重复，比如click -->
        <my-component @some-event="handleSomeEvent" :count="num" ref="childCompnent"> </my-component>
    </div>


    <template id="my-component">
        <div>
            <button @click="triggerEvent">触发自定义事件</button>
            <button>来自父组件的数据:{{count}}</button>
            <div>{{count}}</div>
            <!-- 触发自定义事件$emit('事件名称', 参数) -->
            <button @click="$emit('some-event', msg, count)">触发自定义事件2</button>
        </div>
    </template>


    <!-- 引入vue -->
    <script src=" https://unpkg.com/vue@3/dist/vue.global.js">
    </script>
    <script>

        const { createApp, ref, onMounted, nextTick, getCurrentInstance, useTemplateRef } = Vue;
        // 创建Vue实例
        const app = createApp({
            setup() {
                const num = ref(10)
                const message = ref('')
                const myComponent = useTemplateRef('childCompnent')
                const handleSomeEvent = (data, data2) => {
                    console.log('自定义事件触发了', data, data2);
                    message.value = data
                }
                const changeMessage = () => {
                    message.value = '修改后的消息'
                }
                const changeNumInParent = () => {
                    // console.log(abc.value);
                    myComponent.value.changeCount()

                }
                return {
                    num,
                    handleSomeEvent,
                    message,
                    changeMessage,
                    changeNumInParent
                }
            }
        })

        // 全局注册一个组件
        app.component('my-component', {
            props: ['count'],// 声明属性
            emits: ['some-event'],// 声明自定义事件
            template: "#my-component",
            setup(props, context) {
                const msg = ref("我是子组件的数组")
                const count = ref(10)
                // child组件触发自定义事件
                const triggerEvent = () => {
                    // emit 触发自定义事件
                    // context.emit(事件名称, 参数)
                    context.emit('some-event', msg.value, count.value)
                }
                const changeCount = () => {
                    count.value++
                }
                return {
                    triggerEvent,
                    msg,
                    count,
                    changeCount
                }
            }
        })
        // 挂载到dom
        app.mount('#app')
    </script>
</body>

</html>